package cur.nature.component.redis.controller;

import cur.nature.component.redis.common.RedisUtil;
import cur.nature.framework.core.log.LOG;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 缓存 Controller
 * 作者：Auto Generator By wujian
 * 生成日期：2023-08-05 17:57:55
 */
@Tag(name = "分布式锁 接口")
@RestController
@RequestMapping("component/redis/v1/api/redission")
@ConditionalOnProperty( value = {"cur.component.redis.controller.enable"})
public class Redis_RedissionController {

    @Autowired
    private RedissonClient redissonClient;   // 注入Redisson对象

    @Operation(summary = "设置锁")
    @GetMapping("/set")
    public void set() throws Exception {
        LOG.info("set Redisson");
        final RLock lock = redissonClient.getLock("testLock");
        // 尝试加锁，最多等待2秒，锁定之后最多持有锁6秒
        if (!lock.isLocked() && lock.tryLock(2,6, TimeUnit.SECONDS)) {
//        if (lock.tryLock()) {
            try {
                System.out.println("加锁成功，等待观察redis过期时间是否自动续期");
                TimeUnit.SECONDS.sleep(60);
                System.out.println("休眠结束");
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    System.out.println("释放当前执行线程的锁");
                    lock.unlock();
                }
                System.out.println("解锁成功");
            }
        }
    }

    @Operation(summary = "获取锁")
    @GetMapping("/get")
    public Map<String, String> get() throws Exception {
        LOG.info("get Redisson");
        Map<String, String> resMap = new HashMap<>();
        RedisUtil.set("test", "aaaaa");
        resMap.put("test", (String) RedisUtil.get("test"));
        return resMap;
    }

}

